<template>
  <div>
    <el-card shadow="never">
      <el-skeleton :loading="loading" animated>
        <el-row :gutter="16" justify="space-between">
          <el-col :xl="12" :lg="12" :md="12" :sm="24" :xs="24">
            <div class="flex items-center">
              <el-avatar :src="avatar" :size="70" class="mr-16px">
                <img src="@/assets/imgs/avatar.gif" alt="" />
              </el-avatar>
              <div>
                <div class="text-20px">
                  {{ t('workplace.welcome') }} {{ username }} {{ t('workplace.happyDay') }}
                </div>
                <Weather class="mt-10px" />
              </div>
            </div>
          </el-col>
          <el-col :xl="12" :lg="12" :md="12" :sm="24" :xs="24">
            <div class="h-70px flex items-center justify-end lt-sm:mt-10px">
              <div class="px-8px text-right">
                <div class="mb-16px text-14px text-gray-400">{{ t('workplace.project') }}</div>
                <CountTo
                  class="text-20px"
                  :start-val="0"
                  :end-val="totalSate.project"
                  :duration="2600"
                />
              </div>
              <el-divider direction="vertical" />
              <div class="px-8px text-right">
                <div class="mb-16px text-14px text-gray-400">{{ t('workplace.toDo') }}</div>
                <CountTo
                  class="text-20px"
                  :start-val="0"
                  :end-val="totalSate.todo"
                  :duration="2600"
                />
              </div>
              <el-divider direction="vertical" border-style="dashed" />
              <div class="px-8px text-right">
                <div class="mb-16px text-14px text-gray-400">{{ t('workplace.access') }}</div>
                <CountTo
                  class="text-20px"
                  :start-val="0"
                  :end-val="totalSate.access"
                  :duration="2600"
                />
              </div>
            </div>
          </el-col>
        </el-row>
      </el-skeleton>
    </el-card>
  </div>

  <el-row class="mt-8px" :gutter="8" justify="space-between">
    <el-col :span="24" class="mb-8px">
      <el-row :gutter="8">
        <el-col :span="24">
          <el-card shadow="never" class="mb-8px">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-card shadow="hover" class="mb-8px">
                  <template #header>
                    <div class="card-header">
                      <span class="font-bold text-18px">充值排行榜</span>
                      <el-radio-group v-model="rechargeDays" size="small" @change="getRechargeLank">
                        <el-radio-button :label="7">7天</el-radio-button>
                        <el-radio-button :label="30">30天</el-radio-button>
                        <el-radio-button :label="90">90天</el-radio-button>
                      </el-radio-group>
                    </div>
                  </template>
                  <el-skeleton :loading="loading" :rows="5" animated>
                    <template #default>
                      <div class="rank-list">
                        <div v-for="(item, index) in rechargeRankList" :key="item.userId" class="rank-item">
                          <div class="rank-index" :class="{'rank-top': index === 0}">{{ index + 1 }}</div>
                          <div class="rank-name">{{ item.userName }}</div>
                          <div class="rank-amount">{{ formatAmount(item.totalAmount) }}</div>
                          <div v-if="index === 0" class="rank-icon">🔥</div>
                        </div>
                        <div v-if="rechargeRankList.length === 0" class="no-data">暂无数据</div>
                      </div>
                    </template>
                  </el-skeleton>
                </el-card>
              </el-col>
              <el-col :span="12">
                <el-card shadow="hover" class="mb-8px">
                  <template #header>
                    <div class="card-header">
                      <span class="font-bold text-18px">消费排行榜</span>
                      <el-radio-group v-model="consumeDays" size="small" @change="getConsumeLank">
                        <el-radio-button :label="7">7天</el-radio-button>
                        <el-radio-button :label="30">30天</el-radio-button>
                        <el-radio-button :label="90">90天</el-radio-button>
                      </el-radio-group>
                    </div>
                  </template>
                  <el-skeleton :loading="loading" :rows="5" animated>
                    <template #default>
                      <div class="rank-list">
                        <div v-for="(item, index) in consumeRankList" :key="item.userId" class="rank-item">
                          <div class="rank-index" :class="{'rank-top': index === 0}">{{ index + 1 }}</div>
                          <div class="rank-name">{{ item.userName }}</div>
                          <div class="rank-amount">{{ formatAmount(item.totalAmount) }}</div>
                          <div v-if="index === 0" class="rank-icon">🔥</div>
                        </div>
                        <div v-if="consumeRankList.length === 0" class="no-data">暂无数据</div>
                      </div>
                    </template>
                  </el-skeleton>
                </el-card>
              </el-col>
            </el-row>
          </el-card>
        </el-col>
      </el-row>

      <el-card shadow="never" class="tag-cloud-section">
        <template #header>
          <div class="h-3 flex justify-between">
            <span class="font-bold text-20px">大展堂</span>
          </div>
        </template>
        <el-skeleton :loading="loading" animated>
          <div class="tag-cloud-container">
            <el-row :gutter="30">
              <el-col :xl="8" :lg="8" :md="24" :sm="24" :xs="24">
                <el-card shadow="hover" class="mb-20px tag-cloud-card">
                  <template #header>
                    <div class="card-header">
                      <span class="font-bold text-18px">用户姓名</span>
                    </div>
                  </template>
                  <TagCloud :tags="userNameTags" :radius="180" :height="450" color="#409EFF" />
                </el-card>
              </el-col>
              <el-col :xl="8" :lg="8" :md="24" :sm="24" :xs="24">
                <el-card shadow="hover" class="mb-20px tag-cloud-card">
                  <template #header>
                    <div class="card-header">
                      <span class="font-bold text-18px">宠物姓名</span>
                    </div>
                  </template>
                  <TagCloud :tags="petNameTags" :radius="180" :height="450" color="#67C23A" />
                </el-card>
              </el-col>
              <el-col :xl="8" :lg="8" :md="24" :sm="24" :xs="24">
                <el-card shadow="hover" class="mb-20px tag-cloud-card">
                  <template #header>
                    <div class="card-header">
                      <span class="font-bold text-18px">宠物照片</span>
                    </div>
                  </template>
                  <TagCloud :tags="petPhotoTags" :radius="180" :height="450" color="#F56C6C" :image-size="50" />
                </el-card>
              </el-col>
            </el-row>
          </div>
        </el-skeleton>
      </el-card>

      <el-card shadow="never" class="mt-8px">
        <el-skeleton :loading="loading" animated>
          <el-row :gutter="20" justify="space-between">
            <el-col :xl="10" :lg="10" :md="24" :sm="24" :xs="24">
              <el-card shadow="hover" class="mb-8px">
                <template #header>
                  <div class="card-header">
                    <span class="font-bold text-18px">消费类型数据占比</span>
                  </div>
                </template>
                <el-skeleton :loading="loading" animated>
                  <Echart :options="pieOptionsData" :height="280" />
                </el-skeleton>
              </el-card>
            </el-col>
            <el-col :xl="14" :lg="14" :md="24" :sm="24" :xs="24">
              <el-card shadow="hover" class="mb-8px">
                <template #header>
                  <div class="card-header">
                    <span class="font-bold text-18px">每周店内收入总合</span>
                  </div>
                </template>
                <el-skeleton :loading="loading" animated>
                  <Echart :options="barOptionsData" :height="280" />
                </el-skeleton>
              </el-card>
            </el-col>
          </el-row>
        </el-skeleton>
      </el-card>
    </el-col>
  </el-row>
</template>
<script lang="ts" setup>
import {set} from 'lodash-es'
import {EChartsOption} from 'echarts'

import {useUserStore} from '@/store/modules/user'
// import { useWatermark } from '@/hooks/web/useWatermark'
import type {WorkplaceTotal} from './types'
import {barOptions, pieOptions} from './echarts-data'
import {FinancialFlowApi} from '@/api/javainfo/financialflow'
import Weather from '@/components/Weather/index.vue'
import TagCloud from '@/components/TagCloud/index.vue'
import {TagCloudApi, TagItem} from '@/api/javainfo/tag-cloud'

defineOptions({ name: 'Index' })

const { t } = useI18n()
const userStore = useUserStore()
// const { setWatermark } = useWatermark()
const loading = ref(true)
const avatar = userStore.getUser.avatar
const username = userStore.getUser.nickname
const pieOptionsData = reactive<EChartsOption>(pieOptions) as EChartsOption

// 充值排行榜数据
const rechargeRankList = ref([])
const rechargeDays = ref(7)

// 消费排行榜数据
const consumeRankList = ref([])
const consumeDays = ref(7)

// 标签云数据
const userNameTags = ref<TagItem[]>([])
const petNameTags = ref<TagItem[]>([])
const petPhotoTags = ref<TagItem[]>([])

// 格式化金额（分转元）
const formatAmount = (amount) => {
  if (amount === undefined || amount === null) return '¥0.00'
  return '¥' + (amount / 100).toFixed(2)
}

// 获取充值排行榜数据
const getRechargeLank = async () => {
  try {
    const data = await FinancialFlowApi.getUserRank({
      days: rechargeDays.value,
      amountType: 'RECHARGE'
    })
    rechargeRankList.value = data || []
  } catch (error) {
    console.error('获取充值排行榜数据失败', error)
    rechargeRankList.value = []
  }
}

// 获取消费排行榜数据
const getConsumeLank = async () => {
  try {
    const data = await FinancialFlowApi.getUserRank({
      days: consumeDays.value,
      amountType: 'CONSUME'
    })
    consumeRankList.value = data || []
  } catch (error) {
    console.error('获取消费排行榜数据失败', error)
    consumeRankList.value = []
  }
}

// 获取标签云数据
const getTagCloudData = async () => {
  try {
    // 在实际环境中使用API获取数据
    userNameTags.value = await TagCloudApi.getUserNameTags()
    petNameTags.value = await TagCloudApi.getPetNameTags()
    petPhotoTags.value = await TagCloudApi.getPetPhotoTags()

    // // 使用模拟数据
    // userNameTags.value = TagCloudApi.getMockUserNameTags()
    // petNameTags.value = TagCloudApi.getMockPetNameTags()
    // petPhotoTags.value = TagCloudApi.getMockPetPhotoTags()
  } catch (error) {
    console.error('获取标签云数据失败', error)
    userNameTags.value = []
    petNameTags.value = []
    petPhotoTags.value = []
  }
}

// 获取统计数
let totalSate = reactive<WorkplaceTotal>({
  project: 0,
  access: 0,
  todo: 0
})

const getCount = async () => {
  const data = {
    project: 40,
    access: 2340,
    todo: 10
  }
  totalSate = Object.assign(totalSate, data)
}

// 获取消费类型数据占比
const getConsumptionTypeData = async () => {
  const data = [
    { value: 335, name: '宠物食品' },
    { value: 310, name: '医疗费用' },
    { value: 234, name: '服务费用' },
    { value: 135, name: '玩具用品' },
    { value: 148, name: '服装用品' },
    { value: 98, name: '其他费用' }
  ]
  set(
    pieOptionsData,
    'legend.data',
    data.map((v) => v.name)
  )
  pieOptionsData!.series![0].data = data.map((v) => {
    return {
      name: v.name,
      value: v.value
    }
  })
}
const barOptionsData = reactive<EChartsOption>(barOptions) as EChartsOption

// 获取每周店内收入总合
const getWeeklyIncome = async () => {
  const data = [
    { value: 13253, name: '周一' },
    { value: 34235, name: '周二' },
    { value: 26321, name: '周三' },
    { value: 12340, name: '周四' },
    { value: 24643, name: '周五' },
    { value: 18322, name: '周六' },
    { value: 21324, name: '周日' }
  ]
  set(
    barOptionsData,
    'xAxis.data',
    data.map((v) => v.name)
  )
  set(barOptionsData, 'series', [
    {
      name: '收入金额(元)',
      data: data.map((v) => v.value / 100), // 分转元
      type: 'bar',
      itemStyle: {
        color: function(params) {
          // 根据数值大小设置不同的颜色
          const colorList = ['#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4'];
          return colorList[params.dataIndex % colorList.length];
        }
      },
      label: {
        show: true,
        position: 'top',
        formatter: function(params) {
          return '¥' + params.value.toFixed(2);
        }
      }
    }
  ])

  // 修改Y轴标签格式
  set(barOptionsData, 'yAxis.axisLabel', {
    formatter: function(value) {
      if (value >= 1000) {
        return '¥' + (value / 1000).toFixed(1) + 'k';
      }
      return '¥' + value;
    }
  })
}

const getAllApi = async () => {
  await Promise.all([
    getCount(),
    getConsumptionTypeData(),
    getWeeklyIncome(),
    getRechargeLank(),
    getConsumeLank(),
    getTagCloudData()
  ])
  loading.value = false
}

getAllApi()
</script>

<style lang="scss" scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.tag-cloud-section {
  margin-bottom: 20px;
  padding-bottom: 10px;
}

.tag-cloud-container {
  padding: 10px 0;
}

.tag-cloud-card {
  height: 100%;
  margin-bottom: 20px;
}

.rank-list {
  padding: 0 10px;
}

.rank-item {
  display: flex;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.rank-index {
  width: 24px;
  height: 24px;
  line-height: 24px;
  text-align: center;
  background-color: #f0f0f0;
  border-radius: 50%;
  margin-right: 16px;
  font-weight: bold;
}

.rank-top {
  background-color: #f56c6c;
  color: white;
}

.rank-name {
  flex: 1;
  font-size: 14px;
}

.rank-amount {
  font-weight: bold;
  color: #f56c6c;
  margin-right: 8px;
}

.rank-icon {
  font-size: 20px;
  margin-left: 4px;
}

.no-data {
  text-align: center;
  padding: 20px 0;
  color: #909399;
}
</style>
